package com.example.expresshelp.service;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

import com.example.expresshelp.bean.Address;
import com.example.expresshelp.bean.City;
import com.example.expresshelp.bean.District;
import com.example.expresshelp.bean.Province;
import com.example.expresshelp.db.MySqliteHelper;
import com.example.expresshelp.util.Constance;
import com.example.expresshelp.util.HttpClientHelper;
import com.example.expresshelp.util.Validator;

public class CityService {
	private static final String TAG = "CityService";

	/**
	 * 解析城市信息
	 * 
	 * @param province
	 */
	public static List<City> parseCity(Context context, String pid,
			String pCode, String cityHtml) {
		String newHtml = City.BASE_CITY_URL + cityHtml;
		List<City> cityList = new ArrayList<City>();
		String resultHtml = HttpClientHelper.doPost(newHtml, null, 0);
		if (!Validator.isEffective(resultHtml)) {
			return null;
		}
		Document document = Jsoup.parse(resultHtml);
		Elements cityRows = document.getElementsByClass("citytr");
		for (int i = 0; i < cityRows.size(); i++) {
			City city = new City();
			Element tr = cityRows.get(i);
			Elements tds = tr.getElementsByTag("td");
			// 第一个td里是超链接没和城市代码
			Element codeTd = tds.get(0);
			Element codeA = codeTd.getElementsByTag("a").get(0);
			String hrefHtml = codeA.attr("href");
			// 1101中的01
			String cityCode = codeA.text().substring(2, 4);
			// 第二个td里面有名称
			Element nameTd = tds.get(1);
			Element nameA = nameTd.getElementsByTag("a").get(0);
			String cityName = nameA.text();
			Log.i("express", "cityName - >" + cityCode + cityName);
			long cid = saveToDB(context, pid, cityCode, cityName);
			String districtUrl = newHtml.replace(".html", "/" + pCode
					+ cityCode + ".html");
			List<District> districtList = DistrictService.parseDistrict(
					context, pCode, cid + "", cityCode, districtUrl);
			city.setId(cid + "");
			city.setPid(pid);
			city.setProvinceCode(pCode);
			city.setCode(cityCode);
			city.setName(cityName);
			city.setDistrictList(districtList);
			cityList.add(city);
		}
		return cityList;

	}

	/**
	 * 把城市信息保存到数据库中
	 * 
	 * @param context
	 * @param code
	 * @param name
	 */
	public static long saveToDB(Context context, String provinceCode,
			String cityCode, String cityName) {
		try {
			// 构造参数
			ContentValues values = new ContentValues();
			values.put("pcode", provinceCode);
			values.put("code", cityCode);
			values.put("name", cityName);
			return MySqliteHelper.getInstance(context).insert(
					Constance.CITY_TABLE_NMAE, null, values);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	/**
	 * 通过省份id查询城市列表
	 * 
	 * @param context
	 * @param code
	 * @return
	 */
	public static List<City> getCityByPcode(Context context, String pCode) {
		List<City> list = null;
		String where = " pcode=" + pCode;
		Cursor cursor = MySqliteHelper.getInstance(context).query(
				Constance.CITY_TABLE_NMAE, where);
		if (cursor != null) {
			list = new ArrayList<City>();
			while (cursor.moveToNext()) {
				City city = new City();
				city.setProvinceCode(pCode);
				String code = cursor.getString(cursor.getColumnIndex("code"));
				city.setCode(code);
				List<District> districtList = DistrictService
						.getDistrictByCitycode(context, code);
				city.setDistrictList(districtList);
				city.setName(cursor.getString(cursor.getColumnIndex("name")));
				list.add(city);
			}
		}
		return list;
	}

	/**
	 * 
	 * @param context
	 * @param code
	 * @return
	 */
	public static City find(Context context, String cid) {
		City city = null;
		String where = " id='" + cid + "'";
		Cursor cursor = MySqliteHelper.getInstance(context).query(
				Constance.CITY_TABLE_NMAE, where);
		if (cursor != null) {
			while (cursor.moveToNext()) {
				city = new City();
				city.setId(cursor.getString(cursor.getColumnIndex("id")));
				city.setPid(cursor.getString(cursor.getColumnIndex("pcode")));
				city.setCode(cursor.getString(cursor.getColumnIndex("code")));
				city.setName(cursor.getString(cursor.getColumnIndex("name")));
			}
		}
		return city;
	}

	/**
	 * 
	 * @param context
	 * @param code
	 * @return
	 */
	public static List<Address> getCityByName(Context context, String name) {
		if ((name.equals("市辖区") || name.equals("县"))) {
			return null;
		}
		List<Address> addressList = null;
		List<City> list = null;
		String where = " name like '%" + name + "%'";
		Cursor cursor = MySqliteHelper.getInstance(context).query(
				Constance.CITY_TABLE_NMAE, where);
		if (cursor != null) {
			list = new ArrayList<City>();
			addressList = new ArrayList<Address>();
			while (cursor.moveToNext()) {
				City city = new City();
				Address address = new Address();
				String pcode = cursor.getString(cursor.getColumnIndex("pcode"));
				city.setPid(pcode);
				city.setCode(cursor.getString(cursor.getColumnIndex("code")));
				city.setName(cursor.getString(cursor.getColumnIndex("name")));
				list.add(city);
				address.setFilterAddress(city.getName());
				StringBuffer totalAddress = new StringBuffer();
				Province province = ProvinceService
						.find(context, city.getPid());
				if (province != null) {
					totalAddress.append(",");
					totalAddress.append(province.getName());
				}
				address.setUnfilterAddress(totalAddress.toString());
				addressList.add(address);
			}
		}
		return addressList;
	}
}
